package com.live.proxy;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import com.live.proxy.model.UserModel;
import com.live.proxy.sql.UserDatabase;
import com.live.proxy.tool.GetUtil;
import com.live.proxy.tool.OkHttpUtils;
import com.live.proxy.tool.StatusBarUtils;
import com.live.proxy.view.ToastUtils;

import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {

    TextView login_button;
    EditText login_password;
    EditText login_account;
    UserDatabase userDb;
    UserModel userModel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        StatusBarUtils.setDarkStatusWhite(this,R.color.white);
        login_account = findViewById(R.id.login_account);
        login_password = findViewById(R.id.login_password);
        login_button = findViewById(R.id.login_button);
        userDb = new UserDatabase(getApplicationContext());
        init();
    }
    public void init(){
        userModel = userDb.select();
        if(userModel.getAccount() != null){
            login_account.setText(userModel.getAccount());
            login_password.setText(userModel.getPassword());
        }
        login_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(login_account.getText().toString().isEmpty() || login_password.getText().toString().isEmpty()){
                    ToastUtils.Setinfo(getApplicationContext(),"请输入账号密码",2);
                    return ;
                }
                try {
                    JSONObject appJson = GetUtil.getAppInfo(getApplicationContext());
                    JSONObject json = new JSONObject();
                    json.put("user_account",login_account.getText().toString());
                    json.put("user_password",login_password.getText().toString());
                    json.put("app_info",appJson);
                    getAccount(GetUtil.userPassLogin(),json.toString());
                    login_button.setClickable(false);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        });
    }
    public static final int RRQUEST_FAILURE = 1;
    public static final int RRQUEST_SUCCESS = 2;
    @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case RRQUEST_FAILURE:
                    ToastUtils.Setinfo(getApplicationContext(),msg.obj.toString(),2);
                    login_button.setClickable(true);
                    break;
                case RRQUEST_SUCCESS:
                    try {
                        JSONObject json = new JSONObject(msg.obj.toString());
                        if(json.getInt("code") == 1){
                            //登录成功
                            JSONObject valueJson = json.getJSONObject("data");

                            UserModel model = new UserModel();
                            model.setAccount(login_account.getText().toString());
                            model.setPassword(login_password.getText().toString());
                            model.setNickname(valueJson.getString("nickname"));
                            model.setToken(valueJson.getString("token"));
                            model.setAppId(valueJson.getInt("app_id"));
                            model.setAppName(valueJson.getString("app_name"));
                            model.setAutoType(valueJson.getInt("auto_type"));
                            model.setDirectType(valueJson.getInt("auto_dirtype"));
                            model.setInteYue(valueJson.getInt("inte_yue"));
                            if(userModel.getAccount() != null){
                                //存在该账号
                                userDb.updateUserData(model);
                            }else{
                                //不存在
                                userDb.insert(model);
                            }
                            startActivity(new Intent(getApplicationContext(), HomeActivity.class));
                            finish();
                        }else{
                            //登录失败
                            ToastUtils.Setinfo(getApplicationContext(),json.getString("info"),2);
                            login_button.setClickable(true);
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                    break;
            }
        }
    };
    public void getAccount(String url,String jsonStr){
        OkHttpUtils.sendOkHttpJsonRequest(url, jsonStr,new okhttp3.Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Message message = new Message();
                message.what = RRQUEST_FAILURE;
                message.obj = "【请求异常】请联系管理员";
                handler.sendMessage(message);
            }
            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                String responseData = response.body().string();
                Message message = new Message();
                message.what = RRQUEST_SUCCESS;
                message.obj = responseData;
                handler.sendMessage(message);
            }
        });
    }
}